# Dickstein, Ho, and Mark (2023)
# This script turns tables in CSV format into tables in LaTex format for
# use in the paper. 

# * # * # * # * # * # * #
# PRELIMINARIES         #
# * # * # * # * # * # * #

# libraries
library(stringr)

# * # * # * # * # * # * # * # * # * #
# Make LateX Table Adjusted Code    #
# * # * # * # * # * # * # * # * # * #

IsEven <- function(x){
  return(x %% 2 == 0)
}

perfectshuffle <- function(vec1, vec2){
  l <- length(vec1)
  if(length(vec2) != l){stop("vectors need to be the same length.")}
  vec_out <- rep(NA, 2 * l)
  vec_out[((1:l) * 2 ) - 1] <- vec1
  vec_out[((1:l) * 2 )] <- vec2
  return(vec_out)
}

perfectshuffle_df <- function(df1, df2){
  l <- nrow(df1)
  if(nrow(df2) != l){stop("dataframes need to be the same length.")}
  if(!all(names(df1) == names(df2))){stop("dataframes need to have the same names.")}
  df_out <- rbind(df1, df2)
  df_out[((1:l) * 2 ) - 1, ] <- df1
  df_out[((1:l) * 2 ), ] <- df2
  return(df_out)
}

MakeLatexTableAdj <- function(
  startcodelist, # A list which includes row latex code
  tableinnardslist, # This dataframe list includes rownames and data to be added
  tableinnardsroundvec, # what digits to round by? 
  stderrlist = NULL, #list of T or F if it is a table with std errors
  inbetweencodelistlist = NULL, # A list of lists. Each inside list are lines that separate the table innards parts
  endcodelist, # A list which includes a row of latex code in each element.
  rownames = NULL
){
  if(is.null(stderrlist)){
    stderrlist <- list()
    for(i in seq(tableinnardslist)){
      stderrlist[[i]] <- F
    }
  }
  if(is.null(rownames)){
    rownames <- list()
    for(i in seq(tableinnardslist)){
      rownames[[i]] <- row.names(tableinnardslist[[i]])
    }
  }
  
  for(i in seq_along(startcodelist)){
    cat(paste0(startcodelist[[i]], "\n"))
  }
  for(i in seq_along(tableinnardslist)){
    dataframe <- tableinnardslist[[i]]
    for(j in 1:nrow(dataframe)){
      if((!stderrlist[[i]]) | !IsEven(j)){
        cat(str_replace_all(
          paste0(rownames[[i]][j], 
                 " & ", 
                 paste(format(round(as.numeric(unlist(as.matrix(dataframe)[j,])), tableinnardsroundvec[i]), nsmall = tableinnardsroundvec[i], big.mark = ",", scientific = F), collapse = " & "), 
                 "\\\\\n"), 
          pattern = "NA", 
          replacement = ""))
      } else {
        cat(str_replace_all(
          paste0(rownames[[i]][j], 
                 " & (", 
                 paste(format(round(as.numeric(unlist(as.matrix(dataframe)[j,])), tableinnardsroundvec[i]), nsmall = tableinnardsroundvec[i], big.mark = ",", scientific = F), collapse = ") & ("), 
                       ") \\\\\n"), 
                 pattern = ".(   NA.)", 
                 replacement = ""))
      }
    }
    if(i != length(tableinnardslist)){
      inbetweencodelist <- inbetweencodelistlist[[i]]
      for(k in seq_along(inbetweencodelist)){
        cat(paste0(inbetweencodelist[[k]], "\n"))
      } 
    }
  }
  
  for(i in seq_along(endcodelist)){
    cat(paste0(endcodelist[[i]], "\n"))
  }
}

# * # * # * # * # * # * #
# Calling functions     #
# * # * # * # * # * # * #

#Table 1
source("demographics_table.R")
capture.output(
  demographics_table(),
  file = "../latextables/main_t_sum_stats.tex")

#Table 2
source("insurance_sumstats_table.R")
capture.output(
  insurance_sumstats_table(),
  file = "../latextables/main_t_sum_stats_insurance.tex")
  
# Table 3
source("main_est_table.R")
capture.output(
  main_est_table(),
  file = "../latextables/main_t_main_est.tex")

# Table 4
source("ctftparams_table.R")
capture.output(
  ctftparams_table(),
  file = "../latextables/main_t_ctftparams.tex")
  
# Table 5
source("derived_est_table.R")
capture.output(
  derived_est_table(),
  file = "../latextables/main_t_derived_est.tex")
  
# Table 6
source("prem_setting_table.R")
capture.output(
  prem_setting_table(), 
  file = "../latextables/main_t_premium_set.tex")

# Table 7
source("counterfactual_table1.R")
capture.output(
  counterfactual1_table(),
  file = "../latextables/main_t_ctfls1.tex")

# Table 8
source("counterfactual_table2.R")
capture.output(
  counterfactual2_table(),
  file = "../latextables/main_t_ctfls2.tex")

# Table 9
source("counterfactual_markups_table.R")
capture.output(
  counterfactual_markups_table(),
  file = "../latextables/main_t_ctfl_mrkups.tex")


